package db

import (
	"encoding/json"
	"fmt"
	"qkcoupon/errorcode"
	"qkcoupon/models"
	"reflect"
	"time"

	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

/*
 *@note  获取优惠劵信息
 *@param uid: 用户ID
 *@param ccode: 优惠劵编码
 *@return (*PSQkCouponUserInfoEx,uint): (*PSQkCouponUserInfoEx, 错误码)
 */
func GetCoupon(uid string, mobile string, ccode string) (*models.PSQkCouponUserInfoEx, uint) {
	log.Debugf("uid:%s, mobile:%s, ccode:%s", uid, mobile, ccode)

	sql := "SELECT a.ccode,a.cid,a.uid,a.mobile,a.cstate,a.create_tick,a.use_tick,b.ctype,b.utype,b.lmode,b.bid,b.rwid,b.sum,b.discount,b.max_discount,b.time_range,b.start_tick,b.end_tick FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid"

	if uid != "" && mobile != "" {
		sql += fmt.Sprintf(" WHERE ccode=? AND (uid='%s' or mobile='%s')", uid, mobile)
	} else if uid != "" {
		sql += fmt.Sprintf(" WHERE ccode=? AND uid='%s'", uid)
	} else {
		sql += fmt.Sprintf(" WHERE ccode=? AND mobile='%s'", mobile)
	}

	//log.Debugf("sql:%s", sql)

	list, err := qingkeMysqlHelper.Query(sql, ccode)
	if err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	if len(list) == 0 {
		log.Warn("len(list)==0")
		return nil, errorcode.EC_QKCOUPON_COUPON_NOT_EXIST
	}

	//log.Debug("list:", list)

	uie := &models.PSQkCouponUserInfoEx{}
	uie.UserInfo = &models.PSQkCouponUserInfo{}
	uie.BaseInfo = &models.PSQkCouponBaseInfo{}

	utility.SetTypeValue(list[0]["ccode"], reflect.ValueOf(&uie.UserInfo.Ccode).Elem())
	utility.SetTypeValue(list[0]["cid"], reflect.ValueOf(&uie.UserInfo.Cid).Elem())
	utility.SetTypeValue(list[0]["uid"], reflect.ValueOf(&uie.UserInfo.Uid).Elem())
	utility.SetTypeValue(list[0]["mobile"], reflect.ValueOf(&uie.UserInfo.Mobile).Elem())
	utility.SetTypeValue(list[0]["cstate"], reflect.ValueOf(&uie.UserInfo.Cstate).Elem())
	utility.SetTypeValue(list[0]["create_tick"], reflect.ValueOf(&uie.UserInfo.CreateTick).Elem())
	utility.SetTypeValue(list[0]["use_tick"], reflect.ValueOf(&uie.UserInfo.UseTick).Elem())
	utility.SetTypeValue(list[0]["ctype"], reflect.ValueOf(&uie.BaseInfo.Ctype).Elem())
	utility.SetTypeValue(list[0]["utype"], reflect.ValueOf(&uie.BaseInfo.Utype).Elem())
	utility.SetTypeValue(list[0]["lmode"], reflect.ValueOf(&uie.BaseInfo.Lmode).Elem())
	utility.SetTypeValue(list[0]["bid"], reflect.ValueOf(&uie.BaseInfo.Bid).Elem())
	utility.SetTypeValue(list[0]["sum"], reflect.ValueOf(&uie.BaseInfo.Sum).Elem())
	utility.SetTypeValue(list[0]["discount"], reflect.ValueOf(&uie.BaseInfo.Discount).Elem())
	utility.SetTypeValue(list[0]["max_discount"], reflect.ValueOf(&uie.BaseInfo.MaxDiscount).Elem())
	utility.SetTypeValue(list[0]["start_tick"], reflect.ValueOf(&uie.BaseInfo.StartTick).Elem())
	utility.SetTypeValue(list[0]["end_tick"], reflect.ValueOf(&uie.BaseInfo.EndTick).Elem())

	var rwids []byte
	var timeRange []byte

	utility.SetTypeValue(list[0]["rwid"], reflect.ValueOf(&rwids).Elem())

	if len(rwids) != 0 {
		uie.BaseInfo.Rwids = &models.PCQkCouponRwids{}
		err = json.Unmarshal(rwids, uie.BaseInfo.Rwids)
		//err = proto.Unmarshal(rwids, uie.BaseInfo.Rwids)
		if err != nil {
			log.Warn(err.Error())
		}
	}

	utility.SetTypeValue(list[0]["time_range"], reflect.ValueOf(&timeRange).Elem())

	if len(timeRange) != 0 {
		uie.BaseInfo.TimeRanges = &models.PCQkCouponTimeRanges{}
		err = json.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
		//err = proto.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
		if err != nil {
			log.Warn(err.Error())
		}
	}

	return uie, errorcode.EC_GL_SUCCESS
}

/*
 *@note  获取分享者ID
 *@param share_id: 分享ID
 *@return (string,uint): (分享者ID, 错误码)
 */
func GetSharerId(share_id string) (string, uint) {
	log.Debugf("share_id:%s", share_id)

	sql := "SELECT sharer FROM share_info WHERE share_id=?"

	list, err := qingkeMysqlHelper.Query(sql, share_id)
	if err != nil {
		log.Warn(err.Error())
		return "", errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	if len(list) == 0 {
		log.Warn("len(list)==0")
		return "", errorcode.EC_QKCOUPON_COUPON_NOT_EXIST
	}

	var sharer string

	utility.SetTypeValue(list[0]["sharer"], reflect.ValueOf(&sharer).Elem())

	return sharer, errorcode.EC_GL_SUCCESS
}

/*
 *@note  分页批量获取优惠劵信息列表
 *@param uid: 用户ID
 *@param cstate: 优惠券状态
 *@param ctype: 优惠券类型
 *@param bid: 商家ID
 *@param page_index: 分页偏移
 *@param page_size: 分页数量
 *@param order: 排序
 *@return ([]*PSQkCouponUserCommonList,uint): ([]*PSQkCouponUserCommonList,错误码)
 */
func GetCouponList(uid string, mobile string, cstate int32, ctype int32, bid string, page_index int32, page_size int32, order []string, version int32) (*models.PSQkCouponUserInfoExList, uint) {
	sql := "SELECT a.ccode,a.cid,a.uid,a.cstate,a.create_tick,a.use_tick,b.ctype,b.utype,b.lmode,b.bid,b.rwid,b.sum,b.discount,b.max_discount,b.time_range,b.start_tick,b.end_tick FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid"

	var where bool

	if cstate != 0 {
		now := time.Now().Unix()

		if cstate == int32(models.EQKCOUPON_CSTATE_EXPIRED) {
			sql += fmt.Sprintf(" WHERE cstate!=%d AND end_tick<%d", int32(models.EQKCOUPON_CSTATE_USED), now)
		} else if cstate == int32(models.EQKCOUPON_CSTATE_USED) {
			sql += fmt.Sprintf(" WHERE cstate=%d", cstate)
		} else {
			sql += fmt.Sprintf(" WHERE cstate=%d AND end_tick>%d", cstate, now)
		}

		where = true
	}

	if ctype != 0 {
		if where {
			sql += " AND"
		} else {
			sql += " WHERE"
		}

		sql += fmt.Sprintf(" ctype=%d", ctype)

		where = true
	} else {
		//客户端版本小于6,则不显示代金劵
		if version < 6 {
			if where {
				sql += " AND"
			} else {
				sql += " WHERE"
			}

			sql += " ctype!=4 AND ctype!=5"
			where = true
		}
	}

	if bid != "" {
		if where {
			sql += " AND"
		} else {
			sql += " WHERE"
		}

		sql += fmt.Sprintf(" bid='%s'", bid)
	}

	if uid != "" || mobile != "" {
		if where {
			sql += " AND"
		} else {
			sql += " WHERE"
		}

		if uid != "" && mobile != "" {
			sql += fmt.Sprintf(" (uid='%s' or mobile='%s')", uid, mobile)
		} else if uid != "" {
			sql += fmt.Sprintf(" uid='%s'", uid)
		} else {
			sql += fmt.Sprintf(" mobile='%s'", mobile)
		}
	}

	orderLen := len(order)
	if orderLen > 0 && orderLen < 3 {
		sql += fmt.Sprintf(" ORDER BY %s %s", order[0], order[1])
	}

	if page_size != 0 {
		sql += fmt.Sprintf(" LIMIT %d,%d", page_index, page_size)
	}

	log.Debugf("sql:%s", sql)

	list, err := qingkeMysqlHelper.Query(sql)
	if err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	uiel := &models.PSQkCouponUserInfoExList{}
	uiel.List = make([]*models.PSQkCouponUserInfoEx, len(list))

	for i, row := range list {
		uie := &models.PSQkCouponUserInfoEx{}
		uie.UserInfo = &models.PSQkCouponUserInfo{}
		uie.BaseInfo = &models.PSQkCouponBaseInfo{}

		utility.SetTypeValue(row["ccode"], reflect.ValueOf(&uie.UserInfo.Ccode).Elem())
		utility.SetTypeValue(row["cid"], reflect.ValueOf(&uie.UserInfo.Cid).Elem())
		utility.SetTypeValue(row["uid"], reflect.ValueOf(&uie.UserInfo.Uid).Elem())
		utility.SetTypeValue(row["cstate"], reflect.ValueOf(&uie.UserInfo.Cstate).Elem())
		utility.SetTypeValue(row["create_tick"], reflect.ValueOf(&uie.UserInfo.CreateTick).Elem())
		utility.SetTypeValue(row["use_tick"], reflect.ValueOf(&uie.UserInfo.UseTick).Elem())
		utility.SetTypeValue(row["ctype"], reflect.ValueOf(&uie.BaseInfo.Ctype).Elem())
		utility.SetTypeValue(row["utype"], reflect.ValueOf(&uie.BaseInfo.Utype).Elem())
		utility.SetTypeValue(row["lmode"], reflect.ValueOf(&uie.BaseInfo.Lmode).Elem())
		utility.SetTypeValue(row["bid"], reflect.ValueOf(&uie.BaseInfo.Bid).Elem())
		utility.SetTypeValue(row["sum"], reflect.ValueOf(&uie.BaseInfo.Sum).Elem())
		utility.SetTypeValue(row["discount"], reflect.ValueOf(&uie.BaseInfo.Discount).Elem())
		utility.SetTypeValue(row["max_discount"], reflect.ValueOf(&uie.BaseInfo.MaxDiscount).Elem())
		utility.SetTypeValue(row["start_tick"], reflect.ValueOf(&uie.BaseInfo.StartTick).Elem())
		utility.SetTypeValue(row["end_tick"], reflect.ValueOf(&uie.BaseInfo.EndTick).Elem())

		var rwids []byte
		var timeRange []byte

		utility.SetTypeValue(row["rwid"], reflect.ValueOf(&rwids).Elem())

		if len(rwids) != 0 {
			uie.BaseInfo.Rwids = &models.PCQkCouponRwids{}
			err = json.Unmarshal(rwids, uie.BaseInfo.Rwids)
			//err = proto.Unmarshal(rwids, uie.BaseInfo.Rwids)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		utility.SetTypeValue(row["time_range"], reflect.ValueOf(&timeRange).Elem())

		if len(timeRange) != 0 {
			uie.BaseInfo.TimeRanges = &models.PCQkCouponTimeRanges{}
			err = json.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			//err = proto.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		uiel.List[i] = uie
	}

	return uiel, errorcode.EC_GL_SUCCESS
}

func GetShareCouponList(share_id string) (*models.PSQkCouponShareCouponList, uint) {
	sql := fmt.Sprintf("SELECT mobile,ctype,lmode,sum,discount FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid WHERE ccode IN (SELECT ccode FROM receive_share WHERE share_id=?) ORDER BY create_tick DESC")
	//log.Debugf("sql:%s", sql)

	list, err := qingkeMysqlHelper.Query(sql, share_id)
	if err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	ssl := &models.PSQkCouponShareCouponList{}
	ssl.List = make([]*models.PSQkCouponShareCoupon, len(list))

	for i, row := range list {
		sc := &models.PSQkCouponShareCoupon{}

		utility.SetTypeValue(row["mobile"], reflect.ValueOf(&sc.Mobile).Elem())
		utility.SetTypeValue(row["ctype"], reflect.ValueOf(&sc.Ctype).Elem())
		utility.SetTypeValue(row["lmode"], reflect.ValueOf(&sc.Lmode).Elem())
		utility.SetTypeValue(row["sum"], reflect.ValueOf(&sc.Sum).Elem())
		utility.SetTypeValue(row["discount"], reflect.ValueOf(&sc.Discount).Elem())

		ssl.List[i] = sc
	}

	return ssl, errorcode.EC_GL_SUCCESS
}

/*
 *@note  获取优惠劵总数量
 *@param uid: 用户ID
 *@param cstate: 优惠券状态
 *@param ctype: 优惠券类型
 *@param bid: 商家ID
 *@return (*PCQkCouponInfoCount,uint): (*PCQkCouponInfoCount,错误码)
 */
func GetCouponCount(uid string, mobile string, cstate int32, ctype int32, bid string, version int32) (*models.PCQkCouponInfoCount, uint) {
	sql := "SELECT COUNT(ccode) as ct FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid"

	var where bool
	var params []interface{}

	if cstate != 0 {
		now := time.Now().Unix()

		if cstate == int32(models.EQKCOUPON_CSTATE_EXPIRED) {
			sql += fmt.Sprintf(" WHERE cstate!=%d AND end_tick<%d", int32(models.EQKCOUPON_CSTATE_USED), now)
		} else if cstate == int32(models.EQKCOUPON_CSTATE_USED) {
			sql += fmt.Sprintf(" WHERE cstate=%d", cstate)
		} else {
			sql += fmt.Sprintf(" WHERE cstate=%d AND end_tick>%d", cstate, now)
		}

		where = true
	}

	if ctype != 0 {
		if where {
			sql += " AND "
		} else {
			sql += " WHERE "
		}

		sql += " ctype=?"

		params = append(params, ctype)
		where = true
	} else {
		//客户端版本小于6,则不显示代金劵
		if version < 6 {
			if where {
				sql += " AND"
			} else {
				sql += " WHERE"
			}

			sql += " ctype!=4 AND ctype!=5"
			where = true
		}
	}

	if bid != "" {
		if where {
			sql += " AND "
		} else {
			sql += " WHERE "
		}

		sql += "bid=?"
		params = append(params, bid)
	}

	if uid != "" || mobile != "" {
		if where {
			sql += " AND "
		} else {
			sql += " WHERE "
		}

		if uid != "" && mobile != "" {
			sql += fmt.Sprintf("(uid='%s' OR mobile='%s')", uid, mobile)
		} else if uid != "" {
			sql += fmt.Sprintf("uid='%s'", uid)
		} else {
			sql += fmt.Sprintf("mobile='%s'", mobile)
		}
	}

	log.Debugf("sql:%s", sql)

	cic := &models.PCQkCouponInfoCount{}

	list, err := qingkeMysqlHelper.Query(sql, params...)
	if err != nil {
		return cic, errorcode.EC_QKCOUPON_GET_COUPON_COUNT_FAIL
	}

	if len(list) == 0 {
		log.Warn("len(list) == 0")
		return cic, errorcode.EC_GL_SUCCESS
	}

	utility.SetTypeValue(list[0]["ct"], reflect.ValueOf(&cic.Count).Elem())

	return cic, errorcode.EC_GL_SUCCESS
}

/*
 *@note  获取充值优惠劵信息列表
 *@param uid: 用户ID
 *@param num: 充值轻币值
 *@param usable: 可用与不可用
 *@return ([]*PSQkCouponUserInfoExList,uint): ([]*PSQkCouponUserInfoExList,错误码)
 */
func GetRechargeCouponList(uid string, sum int32, usable int8) (*models.PSQkCouponUserInfoExList, uint) {
	sql := "SELECT a.ccode,a.cid,a.uid,a.cstate,a.create_tick,a.use_tick,b.ctype,b.utype,b.lmode,b.bid,b.rwid,b.sum,b.discount,b.max_discount,b.time_range,b.start_tick,b.end_tick FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid"

	now := time.Now().Unix()

	if usable == 0 {
		//uid='%s' AND cstate=1 AND (ctype!=1 AND end_tick>%d)              //在不可用页面显示：未过期的,不是充值优惠劵
		//uid='%s' AND cstate=1 AND (ctype=1 AND sum>%d AND end_tick>%d)    //在不可用页面显示：未过期的,充值轻币小于优惠劵轻币,是充值优惠劵
		sql += fmt.Sprintf(" WHERE uid='%s' AND cstate=1 AND ((ctype!=1 AND end_tick>%d) OR (ctype=1 AND sum>%d AND end_tick>%d))", uid, now, sum, now)
	} else {
		sql += fmt.Sprintf(" WHERE uid='%s' AND ctype=1 AND cstate=1 AND sum<=%d AND start_tick<=%d AND end_tick>=%d", uid, sum, now, now)
	}

	sql += " ORDER BY sum DESC"

	//log.Debugf("sql:%s", sql)

	list, err := qingkeMysqlHelper.Query(sql)
	if err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	uiel := &models.PSQkCouponUserInfoExList{}
	uiel.List = make([]*models.PSQkCouponUserInfoEx, len(list))

	for i, row := range list {
		uie := &models.PSQkCouponUserInfoEx{}
		uie.UserInfo = &models.PSQkCouponUserInfo{}
		uie.BaseInfo = &models.PSQkCouponBaseInfo{}

		utility.SetTypeValue(row["ccode"], reflect.ValueOf(&uie.UserInfo.Ccode).Elem())
		utility.SetTypeValue(row["cid"], reflect.ValueOf(&uie.UserInfo.Cid).Elem())
		utility.SetTypeValue(row["uid"], reflect.ValueOf(&uie.UserInfo.Uid).Elem())
		utility.SetTypeValue(row["cstate"], reflect.ValueOf(&uie.UserInfo.Cstate).Elem())
		utility.SetTypeValue(row["create_tick"], reflect.ValueOf(&uie.UserInfo.CreateTick).Elem())
		utility.SetTypeValue(row["use_tick"], reflect.ValueOf(&uie.UserInfo.UseTick).Elem())
		utility.SetTypeValue(row["ctype"], reflect.ValueOf(&uie.BaseInfo.Ctype).Elem())
		utility.SetTypeValue(row["utype"], reflect.ValueOf(&uie.BaseInfo.Utype).Elem())
		utility.SetTypeValue(row["lmode"], reflect.ValueOf(&uie.BaseInfo.Lmode).Elem())
		utility.SetTypeValue(row["bid"], reflect.ValueOf(&uie.BaseInfo.Bid).Elem())
		utility.SetTypeValue(row["sum"], reflect.ValueOf(&uie.BaseInfo.Sum).Elem())
		utility.SetTypeValue(row["discount"], reflect.ValueOf(&uie.BaseInfo.Discount).Elem())
		utility.SetTypeValue(row["max_discount"], reflect.ValueOf(&uie.BaseInfo.MaxDiscount).Elem())
		utility.SetTypeValue(row["start_tick"], reflect.ValueOf(&uie.BaseInfo.StartTick).Elem())
		utility.SetTypeValue(row["end_tick"], reflect.ValueOf(&uie.BaseInfo.EndTick).Elem())

		var rwids []byte
		var timeRange []byte

		utility.SetTypeValue(row["rwid"], reflect.ValueOf(&rwids).Elem())

		if len(rwids) != 0 {
			uie.BaseInfo.Rwids = &models.PCQkCouponRwids{}
			err = json.Unmarshal(rwids, uie.BaseInfo.Rwids)
			//err = proto.Unmarshal(rwids, uie.BaseInfo.Rwids)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		utility.SetTypeValue(row["time_range"], reflect.ValueOf(&timeRange).Elem())

		if len(timeRange) != 0 {
			uie.BaseInfo.TimeRanges = &models.PCQkCouponTimeRanges{}
			err = json.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			//err = proto.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		uiel.List[i] = uie
	}

	return uiel, errorcode.EC_GL_SUCCESS
}

/*
 *@note  获取洗衣优惠劵信息列表
 *@param uid: 用户ID
 *@param lmode: 洗衣模式
 *@param num: 充值轻币值
 *@param usable: 可用与不可用
 *@return ([]*PSQkCouponUserInfoExList,uint): ([]*PSQkCouponUserInfoExList,错误码)
 */
func GetLaundryCouponList(uid string, lmode int32, sum int32, usable int8) (*models.PSQkCouponUserInfoExList, uint) {
	sql := "SELECT a.ccode,a.cid,a.uid,a.cstate,a.create_tick,a.use_tick,b.ctype,b.utype,b.lmode,b.bid,b.rwid,b.sum,b.discount,b.max_discount,b.time_range,b.start_tick,b.end_tick FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid"

	now := time.Now().Unix()

	if usable == 0 {
		//uid='%s' AND cstate=1 AND (ctype!=2 AND ctype!=3 AND end_tick>%d)     //在不可用页面显示：未过期的,不是折扣优惠劵和不是免费优惠劵
		//uid='%s' AND cstate=1 AND ((lmode!=%d AND lmode!=0) AND end_tick>%d)  //在不可用页面显示：未过期的,洗衣模式等于全部和不等于某洗衣模式
		//uid='%s' AND cstate=1 AND ((lmode=%d OR lmode=0) AND start_tick>%d)   //在不可用页面显示：不可用的,洗衣模式等于某洗衣模式或全部
		sql += fmt.Sprintf(" WHERE uid='%s' AND cstate=1 AND ((ctype!=2 AND ctype!=3 AND end_tick>%d) OR ((lmode!=%d AND lmode!=0) AND end_tick>%d) OR ((lmode=%d OR lmode=0) AND start_tick>%d))", uid, now, lmode, now, lmode, now)
	} else {
		sql += fmt.Sprintf(" WHERE uid='%s' AND (ctype=2 OR ctype=3) AND cstate=1 AND (lmode=0 OR lmode=%d) AND start_tick<=%d AND end_tick>=%d", uid, lmode, now, now)
	}

	sql += " ORDER BY ctype DESC"

	//log.Debugf("sql:%s", sql)

	list, err := qingkeMysqlHelper.Query(sql)
	if err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	uiel := &models.PSQkCouponUserInfoExList{}
	uiel.List = make([]*models.PSQkCouponUserInfoEx, len(list))

	for i, row := range list {
		uie := &models.PSQkCouponUserInfoEx{}
		uie.UserInfo = &models.PSQkCouponUserInfo{}
		uie.BaseInfo = &models.PSQkCouponBaseInfo{}

		utility.SetTypeValue(row["ccode"], reflect.ValueOf(&uie.UserInfo.Ccode).Elem())
		utility.SetTypeValue(row["cid"], reflect.ValueOf(&uie.UserInfo.Cid).Elem())
		utility.SetTypeValue(row["uid"], reflect.ValueOf(&uie.UserInfo.Uid).Elem())
		utility.SetTypeValue(row["cstate"], reflect.ValueOf(&uie.UserInfo.Cstate).Elem())
		utility.SetTypeValue(row["create_tick"], reflect.ValueOf(&uie.UserInfo.CreateTick).Elem())
		utility.SetTypeValue(row["use_tick"], reflect.ValueOf(&uie.UserInfo.UseTick).Elem())
		utility.SetTypeValue(row["ctype"], reflect.ValueOf(&uie.BaseInfo.Ctype).Elem())
		utility.SetTypeValue(row["utype"], reflect.ValueOf(&uie.BaseInfo.Utype).Elem())
		utility.SetTypeValue(row["lmode"], reflect.ValueOf(&uie.BaseInfo.Lmode).Elem())
		utility.SetTypeValue(row["bid"], reflect.ValueOf(&uie.BaseInfo.Bid).Elem())
		utility.SetTypeValue(row["sum"], reflect.ValueOf(&uie.BaseInfo.Sum).Elem())
		utility.SetTypeValue(row["discount"], reflect.ValueOf(&uie.BaseInfo.Discount).Elem())
		utility.SetTypeValue(row["max_discount"], reflect.ValueOf(&uie.BaseInfo.MaxDiscount).Elem())
		utility.SetTypeValue(row["start_tick"], reflect.ValueOf(&uie.BaseInfo.StartTick).Elem())
		utility.SetTypeValue(row["end_tick"], reflect.ValueOf(&uie.BaseInfo.EndTick).Elem())

		var rwids []byte
		var timeRange []byte

		utility.SetTypeValue(row["rwid"], reflect.ValueOf(&rwids).Elem())

		if len(rwids) != 0 {
			uie.BaseInfo.Rwids = &models.PCQkCouponRwids{}
			err = json.Unmarshal(rwids, uie.BaseInfo.Rwids)
			//err = proto.Unmarshal(rwids, uie.BaseInfo.Rwids)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		utility.SetTypeValue(row["time_range"], reflect.ValueOf(&timeRange).Elem())

		if len(timeRange) != 0 {
			uie.BaseInfo.TimeRanges = &models.PCQkCouponTimeRanges{}
			err = json.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			//err = proto.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		uiel.List[i] = uie
	}

	return uiel, errorcode.EC_GL_SUCCESS
}

/*
 *@note  获取优惠劵信息列表
 *@param uid: 用户ID
 *@return ([]*PSQkCouponUserInfoExList,uint): ([]*PSQkCouponUserInfoExList,错误码)
 */
func GetCouponListByUid(uid string, mobile string) (*models.PSQkCouponUserInfoExList, uint) {
	sql := "SELECT a.ccode,a.cid,a.uid,a.cstate,a.create_tick,a.use_tick,b.ctype,b.utype,b.lmode,b.bid,b.rwid,b.sum,b.discount,b.max_discount,b.time_range,b.start_tick,b.end_tick FROM coupon_info b LEFT JOIN user_coupon a ON a.cid=b.cid"

	if uid != "" && mobile != "" {
		sql += fmt.Sprintf(" WHERE uid='%s' OR mobile='%s'", uid, mobile)
	} else if uid != "" {
		sql += fmt.Sprintf(" WHERE uid='%s'", uid)
	} else {
		sql += fmt.Sprintf(" WHERE mobile='%s'", mobile)
	}

	sql += "ORDER BY sum DESC"

	//log.Debugf("sql:%s", sql)

	list, err := qingkeMysqlHelper.Query(sql)
	if err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_QKCOUPON_GET_COUPON_FAIL
	}

	uiel := &models.PSQkCouponUserInfoExList{}
	uiel.List = make([]*models.PSQkCouponUserInfoEx, len(list))

	for i, row := range list {
		uie := &models.PSQkCouponUserInfoEx{}
		uie.UserInfo = &models.PSQkCouponUserInfo{}
		uie.BaseInfo = &models.PSQkCouponBaseInfo{}

		utility.SetTypeValue(row["ccode"], reflect.ValueOf(&uie.UserInfo.Ccode).Elem())
		utility.SetTypeValue(row["cid"], reflect.ValueOf(&uie.UserInfo.Cid).Elem())
		utility.SetTypeValue(row["uid"], reflect.ValueOf(&uie.UserInfo.Uid).Elem())
		utility.SetTypeValue(row["cstate"], reflect.ValueOf(&uie.UserInfo.Cstate).Elem())
		utility.SetTypeValue(row["create_tick"], reflect.ValueOf(&uie.UserInfo.CreateTick).Elem())
		utility.SetTypeValue(row["use_tick"], reflect.ValueOf(&uie.UserInfo.UseTick).Elem())
		utility.SetTypeValue(row["ctype"], reflect.ValueOf(&uie.BaseInfo.Ctype).Elem())
		utility.SetTypeValue(row["utype"], reflect.ValueOf(&uie.BaseInfo.Utype).Elem())
		utility.SetTypeValue(row["lmode"], reflect.ValueOf(&uie.BaseInfo.Lmode).Elem())
		utility.SetTypeValue(row["bid"], reflect.ValueOf(&uie.BaseInfo.Bid).Elem())
		utility.SetTypeValue(row["sum"], reflect.ValueOf(&uie.BaseInfo.Sum).Elem())
		utility.SetTypeValue(row["discount"], reflect.ValueOf(&uie.BaseInfo.Discount).Elem())
		utility.SetTypeValue(row["max_discount"], reflect.ValueOf(&uie.BaseInfo.MaxDiscount).Elem())
		utility.SetTypeValue(row["start_tick"], reflect.ValueOf(&uie.BaseInfo.StartTick).Elem())
		utility.SetTypeValue(row["end_tick"], reflect.ValueOf(&uie.BaseInfo.EndTick).Elem())

		var rwids []byte
		var timeRange []byte

		utility.SetTypeValue(row["rwid"], reflect.ValueOf(&rwids).Elem())

		if len(rwids) != 0 {
			uie.BaseInfo.Rwids = &models.PCQkCouponRwids{}
			err = json.Unmarshal(rwids, uie.BaseInfo.Rwids)
			//err = proto.Unmarshal(rwids, uie.BaseInfo.Rwids)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		utility.SetTypeValue(row["time_range"], reflect.ValueOf(&timeRange).Elem())

		if len(timeRange) != 0 {
			//log.Debugf("PCQkCouponTimeRanges:%s", string(timeRange))

			uie.BaseInfo.TimeRanges = &models.PCQkCouponTimeRanges{}
			err = json.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			//err = proto.Unmarshal(timeRange, uie.BaseInfo.TimeRanges)
			if err != nil {
				log.Warn(err.Error())
			}
		}

		uiel.List[i] = uie
	}

	return uiel, errorcode.EC_GL_SUCCESS
}
